package org.yang.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.yang.reggie.common.R;
import org.yang.reggie.dto.DishDto;
import org.yang.reggie.entity.Category;
import org.yang.reggie.entity.Dish;
import org.yang.reggie.entity.DishFlavor;
import org.yang.reggie.service.CategoryService;
import org.yang.reggie.service.DishFlavorService;
import org.yang.reggie.service.DishService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 缘友一世
 * date 2023/5/14-15:37
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryService categoryService;

    @Value("${image.savePath}")
    private String savePath;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理某个缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    /**
     * 查询菜品列表
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name,
                        @RequestParam(value = "isDeleted", required = false) Integer isDeleted) {
        //分页构造器
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.like(name!=null,Dish::getName,name);
        /* if(isDeleted!=null) {
            queryWrapper.eq( Dish::getIsDeleted, isDeleted);
        }else {
            queryWrapper.eq(Dish::getIsDeleted,0);
        } */
        //判断是否删除
        queryWrapper.eq( Dish::getIsDeleted, isDeleted);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //调用service.page方法，执行分页查询
        dishService.page(pageInfo,queryWrapper);
        //菜品分类categoryId与前端需要展示的内容不匹配categoryName
        //解决方法：使用dishDto继承dish实体类增加的categoryName属性进行解决
        //原来的pageInfoRecords没有菜品分类属性，所以把原来的records取出来，扩展一下，做新的dishDtoPageRecords

        //对象拷贝，封装dishDtoPage
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        //封装DishDto
        List<DishDto> dishDtoList=records.stream().map((item)->{
            DishDto dishDto=new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category!=null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        //清理某个缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }

    /**
     * 修改菜品的售出状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<List<Dish>> getStatus(@PathVariable("status") int status, @RequestParam("ids") List<String> ids) {
        List<Dish> updatedDishes = new ArrayList<>();
        for (String id : ids) {
            Dish dish = dishService.getById(Long.valueOf(id));
            if (dish != null) {
                dish.setStatus(status);
                dishService.updateById(dish);
                updatedDishes.add(dish);
            }
        }

        for (Dish dish : updatedDishes) {
            //清理某个缓存数据
            String key="dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }

        return R.success(updatedDishes);
    }

    /**
     * 逻辑删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
                //删除记录
                //dishService.removeById(ids);

                //逻辑删除
                dish.setIsDeleted(1); // 设置逻辑删除标志为true
                dishService.updateById(dish);

                //清理某个缓存数据
                String key="dish_"+dish.getCategoryId()+"_1";
                redisTemplate.delete(key);
        }

        return R.success("删除成功");
    }

    /**
     * 物理删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    public R<String> Delete(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);

            //删除存储的图片
            String image = dish.getImage();
            String imagePosition= savePath+image;
            File imageFile = new File(imagePosition);
            if (imageFile.exists()) {
                boolean deleted = imageFile.delete();
                if (deleted) {
                    log.info("图片删除成功！");
                } else {
                    log.info("图片删除失败！");
                }
            } else {
                log.info("图片文件不存在！");
            }

            //删除记录
            dishService.removeById(id);

        }
        return R.success("删除成功");
    }

    /**
     * 逻辑删除菜品
     * @param isDeleted
     * @param ids
     * @return
     */
    @PostMapping("/isDeleted/{isDeleted}")
    public R<List<Dish>> getIsDeleted(@PathVariable("isDeleted") int isDeleted, @RequestParam("ids") List<String> ids) {
        List<Dish> updatedDishes = new ArrayList<>();
        for (String id : ids) {
            Dish dish = dishService.getById(Long.valueOf(id));
            if (dish != null) {
                dish.setIsDeleted(isDeleted);
                dishService.updateById(dish);
                updatedDishes.add(dish);
            }
        }

        return R.success(updatedDishes);
    }


    /* @GetMapping("/list")
    public R<List<Dish>> getDishList(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询条件起售和未逻辑删除的菜品
         queryWrapper.eq(Dish::getStatus,1);
         queryWrapper.eq(Dish::getIsDeleted,0);
        //添加排序顺序
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    } */
    /**
     * 根据菜品分类查询菜品
     * @param dish 使用实体类进行接收参数，
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getDishList(Dish dish) {
        List<DishDto> dishDtoList=null;
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //从redis中获取缓存的数据
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null) {
            //如果存在直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        //如果不存在，先查询数据库，然后缓存到redis
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询条件起售和未逻辑删除的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(Dish::getIsDeleted,0);
        //添加排序顺序
        List<Dish> list = dishService.list(queryWrapper);

         dishDtoList=list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            //select * from dish_flavor where dish_id =?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

         //缓存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
